package com.yhn.init.bizmq;

import cn.hutool.core.util.StrUtil;
import com.rabbitmq.client.Channel;
import com.yhn.init.common.ErrorCode;
import com.yhn.init.constant.MQConstant;
import com.yhn.init.exception.BusinessException;
import com.yhn.init.model.entity.Orders;
import com.yhn.init.service.OrdersService;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 订单消费者(设计师接收消息，完善订单)
 *
 * @author yhn
 * @version 1.0
 * @description
 * @date 2024/3/15 10:11
 */
@Component
public class OrderMqConsumer {

    @Resource
    private OrdersService ordersService;

    /**
     * 指定程序监听的消息队列和确认机制
     *
     * @param message     确认接收的消息
     * @param channel     消息所在的通道，可以通过该通道与RabbitMQ交互，如手动确认拒绝消息
     * @param deliveryTag 消息的投递标签，用于唯一标识一条消息
     */

    @SneakyThrows
    @RabbitListener(queues = {MQConstant.ORDER_QUEUE_NAME}, ackMode = "MANUAL")
    private void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        if (StrUtil.isBlank(message)) {
            //如果接收到空消息则拒绝消息
            channel.basicNack(deliveryTag, false, true);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接受到的消息为空");
        }
        // 获取到订单的id,
        long orderId = Long.parseLong(message);
        Orders orders = ordersService.getById(orderId);
        if (orders == null) {
            // 将消息拒绝
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "订单为空");
        }

        // 成功，则确认消息
        channel.basicAck(deliveryTag, false);
    }
}
